'use strict';

define(['angular', 'moment', 'angular-ui-router', '../../../common/utils/service', 'readable-range', '../../login/login', '../change-password/change-password', '../pay/pay'],
	function (angular, moment) {
		var module = angular.module('memberProfileCenter', ['ui.router', 'dataService', 'login', 'memberChangePassword', 'memberPay']);
		module.config(['$stateProvider', function ($stateProvider) {
			$stateProvider
				.state("member.profile", {
					url: '/profile',
					views: {
						"@": {
							controller: 'MemberProfileCtrl',
							templateUrl: '/mstore/member/profile/profile.html'
						}
					}
				})
			$stateProvider
				.state("member.oldProfile", {
					url: '/member-profile',
					views: {
						"@": {
							controller: 'MemberOldProfileCtrl'
						}
					}
				})
		}]);
//TODO 以后会删除
		module.controller('MemberOldProfileCtrl', ['$state', function ($state) {
			$state.transitionTo('member.profile')
		}])
		module.controller('MemberProfileCtrl', ['$rootScope', '$state', '$scope', 'dataService', '$mdDialog', function ($rootScope, $state, $scope, dataService, $mdDialog) {
			$rootScope.pageTitle = "会员信息";
			$scope.bindNames = [{name: '微信', id: 'wechat'}]
			$scope.memberBound(function () {
				dataService.getMemberInfo(sessionStorage.memberId, function (err, dataObj) {
					if (err) {
						$state.transitionTo("login");
						return;
					}
					$scope.dataObj = dataObj;
				})
				dataService.getBindList(sessionStorage.memberId, sessionStorage.store, function (err, dataObj) {
					if (err) {
						return;
					}
					$scope.bindList = dataObj;

				})


				$scope.isBind = function (bindName) {
					var result = false;
					angular.forEach($scope.bindList, function (bind) {
						if (bind.sns == bindName.id) {
							result = true;
							return;
						}
					})
					return result;
				}


				$scope.showConfirm = function (bindName) {
					var confirm = $mdDialog.confirm({timeout: 50})
						.title('取消会员微信账号绑定')
						.content('微信账号绑定可以让您使用微信查询会员信息时无需进行会员登录。取消微信绑定？')
						.ok('确定')
						.cancel('取消');
					$mdDialog.show(confirm).then(function () {
						$scope.unBind(bindName);
					}, function () {
						$mdDialog.cancel();
					});
				};
				$scope.unBind = function (bindName) {
					for (var i in $scope.bindList) {
						if ($scope.bindList[i].sns == bindName.id) {
							dataService.unBindMember($scope.bindList[i].id, function (err, data) {
								if (err) {
									$rootScope.showMessage(data);
								}
								$scope.bindList.splice(i, 1);
								$rootScope.showMessage('已解除绑定，你可以通过再次使用会员登录进行绑定。');
							})
							return;
						}
					}
				}
			}, {force: true})
		}]);

		module.filter('bindSns', [function (otype) {
			return function (otype) {
				if (otype == 'wechat') return "微信";
				else return otype;
			}
		}]);
		module.filter('memberSex', [function (otype) {
			return function (otype) {
				if (otype == 1) return "女";
				else if (otype == 0) return "男";
				else return otype;
			}
		}]);
	});
